package com.sqtracker.recommender.service;

import com.sqtracker.recommender.dto.UserBehaviorDTO;
import com.sqtracker.recommender.model.UserBehavior;
import com.sqtracker.recommender.repository.UserBehaviorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserBehaviorService {

    private static final Logger logger = LoggerFactory.getLogger(UserBehaviorService.class);

    private final UserBehaviorRepository userBehaviorRepository;
    private final List<String> SUPPORTED_BEHAVIOR_TYPES = Arrays.asList("VIEW", "LIKE", "DOWNLOAD", "RATE", "REPORT","VIEW_SIMILAR","SEARCH");

    @Autowired
    public UserBehaviorService(UserBehaviorRepository userBehaviorRepository) {
        this.userBehaviorRepository = userBehaviorRepository;
    }

    /**
     * 记录单个用户行为
     */
    public void recordBehavior(UserBehaviorDTO behaviorDTO) {
        logger.info("接收到用户行为记录请求: {}", behaviorDTO);

        if (!isValidBehaviorType(behaviorDTO.getType())) {
            logger.warn("不支持的行为类型: {}", behaviorDTO.getType());
            throw new IllegalArgumentException("不支持的行为类型: " + behaviorDTO.getType());
        }

        UserBehavior behavior = convertDtoToEntity(behaviorDTO);
        userBehaviorRepository.save(behavior);

        logger.info("已保存用户行为: userId={}, type={}, torrentId={}", behavior.getUserId(), behavior.getType(), behavior.getTorrentId());
    }

    /**
     * 批量记录用户行为
     */
    public void recordBehaviorsBatch(UserBehaviorDTO[] behaviorsDTO) {
        logger.info("批量记录用户行为，接收到 {} 条数据", behaviorsDTO.length);

        List<UserBehavior> behaviors = Arrays.stream(behaviorsDTO)
                .filter(dto -> {
                    boolean valid = isValidBehaviorType(dto.getType());
                    if (!valid) {
                        logger.warn("跳过无效行为类型: {}", dto.getType());
                    }
                    return valid;
                })
                .map(this::convertDtoToEntity)
                .collect(Collectors.toList());

        userBehaviorRepository.saveAll(behaviors);
        logger.info("成功保存 {} 条有效用户行为记录", behaviors.size());
    }

    /**
     * 获取用户行为历史
     */
    public List<UserBehavior> getUserBehaviors(String userId, int limit, int skip) {
        logger.info("获取用户 {} 的行为记录: limit={}, skip={}", userId, limit, skip);
        return userBehaviorRepository.findByUserId(userId)
                .stream()
                .skip(skip)
                .limit(limit)
                .collect(Collectors.toList());
    }

    /**
     * 获取用户交互总数
     */
    public long getUserInteractionCount(String userId) {
        long count = userBehaviorRepository.countByUserId(userId);
        logger.info("用户 {} 的总交互数为 {}", userId, count);
        return count;
    }

    /**
     * 获取用户点击数（VIEW类型）
     */
    public long getUserClickCount(String userId) {
        long count = userBehaviorRepository.countByUserIdAndType(userId, "VIEW");
        logger.info("用户 {} 的点击（VIEW）数为 {}", userId, count);
        return count;
    }

    /**
     * 获取支持的行为类型
     */
    public List<String> getSupportedBehaviorTypes() {
        return SUPPORTED_BEHAVIOR_TYPES;
    }

    /**
     * 检查行为类型是否有效
     */
    private boolean isValidBehaviorType(String type) {
        return SUPPORTED_BEHAVIOR_TYPES.contains(type);
    }

    /**
     * 将DTO转换为实体对象
     */
    private UserBehavior convertDtoToEntity(UserBehaviorDTO dto) {
        UserBehavior behavior = new UserBehavior();
        behavior.setUserId(dto.getUserId());
        behavior.setTorrentId(dto.getTorrentId());
        behavior.setType(dto.getType());
        behavior.setRating(dto.getRating());
        behavior.setTimestamp(dto.getTimestamp());
        behavior.setDuration(dto.getDuration());

        UserBehavior.BehaviorContext context = new UserBehavior.BehaviorContext();
        if (dto.getContext() != null) {
            context.setReferrer(dto.getContext().getReferrer());
            context.setQuery(dto.getContext().getQuery());
            context.setDevice(dto.getContext().getDevice());
        }
        behavior.setContext(context);

        return behavior;
    }
}
